package com.arui.security;

import com.alibaba.fastjson.annotation.JSONField;
import com.arui.domain.AruioUser;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description TODO
 * @Date 2024/8/27 15:21
 * @Created by 10574
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class AruioUserDetail implements UserDetails {
    private AruioUser aruioUser;
    private List<String> roleList;

    @JSONField(serialize = false)
    private List<GrantedAuthority> authorities;

    public AruioUserDetail(AruioUser aruioUser, List<String> roleList) {
        this.aruioUser = aruioUser;
        this.roleList = roleList;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (!CollectionUtils.isEmpty(authorities)) {
            return authorities;
        }
        if (CollectionUtils.isEmpty(roleList)) {
            return null;
        }
        authorities = roleList.stream()
                .map((role) -> new SimpleGrantedAuthority("ROLE_" + role))
                .collect(Collectors.toList());
        return authorities;
    }

    @Override
    public String getPassword() {
        return aruioUser.getPassword();
    }

    @Override
    public String getUsername() {
        return aruioUser.getName();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
